package com.data.mall.kafka;

import com.alibaba.fastjson.JSON;
import com.data.mall.repositry.ItemStockRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author shixukai
 * @Package com.data.mall.kafka
 * @Description: TODO
 * @date 2021/5/3
 */
@Slf4j
@Component
public class KafkaServiceConsumer {
    @Autowired
    private ItemStockRepository itemStockRepository;

    @KafkaListener(id= "service1" ,topics = {"service"}, groupId = "service")
    public void onMessageConsumer(ConsumerRecord<?, ?> record) {
        // 消费的哪个topic、partition的消息,打印出消息内容
        log.info("简单消费：" + record.topic() + "-" + record.partition() + "-" + record.value());
        String message = (String) record.value();
        Map<String ,Object> map = JSON.parseObject(message, Map.class);
        Long itemId = (Long) map.get("itemId");
        Integer amount = (Integer) map.get("amount");

        itemStockRepository.decreaseStock(itemId,amount);
    }
}
